package com.example.lib_common.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import androidx.core.content.ContextCompat
import com.example.lib_common.R
import com.example.lib_common.dp


/**
 * @author Wcj
 * @description
 * @date 2022/7/1 14:09
 */
class SharpView : View {
    private var mWidth = 0 //三角形的宽度
    private var mHeight = 0 //三角形的高度
    private var mContext: Context
    private val mFillPaint = Paint()
    private val mStokePaint = Paint()

    private var fill = false

    constructor(context: Context) : this(context, null)


    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        mContext = context
        val typedValue = TypedValue()
        context.theme.resolveAttribute(R.attr.colorBgPopupWindow, typedValue, true)
        val attributes = context.obtainStyledAttributes(attrs, R.styleable.SharpView)
        mStokePaint.color = attributes.getColor(R.styleable.SharpView_sjv_color, ContextCompat.getColor(context, typedValue.resourceId))
        mFillPaint.color = attributes.getColor(R.styleable.SharpView_fill_color, Color.WHITE)
        fill = attributes.getBoolean(R.styleable.SharpView_fill, false)
        initView()
        attributes.recycle()
    }

    private fun initView() {
        mWidth = 18.dp
        mHeight = 10.dp

        mStokePaint.isAntiAlias = true
        mStokePaint.style = Paint.Style.STROKE
        mStokePaint.strokeWidth = 0.5f.dp

        mFillPaint.isAntiAlias = true
        mFillPaint.style = Paint.Style.FILL
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)


        val path2 = Path()
        path2.moveTo(0f, mHeight.toFloat())
        path2.lineTo(mWidth.toFloat(), mHeight.toFloat())
        path2.lineTo(mWidth.toFloat() / 2, 0f)
        path2.close()
        canvas.drawPath(path2, mFillPaint)
        if (!fill) {
            //创建路径
            val path = Path()
            path.moveTo(0f, mHeight.toFloat())
            path.lineTo(mWidth / 2f, 0f)
            path.lineTo(mWidth.toFloat(), mHeight.toFloat())
            canvas.drawPath(path, mStokePaint)
        }
    }
}